package service

import (
	"context"

	pb "glmall-product/api/category"
	"glmall-product/internal/biz"

	"github.com/go-kratos/kratos/v2/log"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type CategoryService struct {
	pb.UnimplementedCategoryServer
	cg *biz.CategoryUsecase
}

func NewCategoryService(cg *biz.CategoryUsecase) *CategoryService {
	return &CategoryService{cg: cg}
}

// 找到所有指定级别分类
func (s *CategoryService) filterByParent(categories []*biz.PmsCategory, parentID int64) []*biz.PmsCategory {
	var result []*biz.PmsCategory
	for _, cat := range categories {
		if int64(*cat.ParentCid) == parentID {
			result = append(result, cat)
		}
	}
	return result
}

// 辅助函数：递归构建分类树
func (s *CategoryService) buildCategoryTree(categoryMap map[int32][]*pb.CategoryInfo, parentId int32) []*pb.CategoryInfo {
	categories, ok := categoryMap[parentId]
	if !ok {
		return nil
	}

	for _, cat := range categories {
		// 递归查找子分类
		cat.Children = s.buildCategoryTree(categoryMap, cat.CatId)
	}

	return categories
}

// 辅助函数：bool转int32（用于ShowStatus）
func (s *CategoryService) boolToInt32(b bool) int32 {
	if b {
		return 1
	}
	return 0
}

func (s *CategoryService) ListCategoryTree(ctx context.Context, req *pb.ListCategoryTreeRequest) (*pb.ListCategoryTreeResponse, error) {
	// 1. 安全获取数据
	dbCategories, err := s.cg.ListWithTree(ctx)
	if err != nil {
		log.Errorf("ListCategoryTree->ListWithTree error: %v", err)
		return &pb.ListCategoryTreeResponse{
			Code: 500,
			Msg:  "获取分类数据失败",
		}, status.Error(codes.Internal, "internal server error")
	}

	// 2. 防御性数据检查
	if len(dbCategories) == 0 {
		return &pb.ListCategoryTreeResponse{
			Code: 200,
			Msg:  "success",
			Data: []*pb.CategoryInfo{},
		}, nil
	}

	// 3. 安全构建分类映射表
	categoryMap := make(map[int32][]*pb.CategoryInfo)
	for _, dbCat := range dbCategories {
		// 关键字段安全检查
		if dbCat == nil || dbCat.CatId == nil || dbCat.Name == nil ||
			dbCat.ParentCid == nil || dbCat.CatLevel == nil ||
			dbCat.ShowStatus == nil || dbCat.Sort == nil ||
			dbCat.ProductCount == nil {
			log.Warnf("invalid category data: %+v", dbCat)
			continue
		}

		// 安全转换
		pbCat := &pb.CategoryInfo{
			CatId:        int32(*dbCat.CatId),
			Name:         *dbCat.Name,
			ParentCid:    int32(*dbCat.ParentCid),
			CatLevel:     int32(*dbCat.CatLevel),
			ShowStatus:   s.boolToInt32(*dbCat.ShowStatus),
			Icon:         nil,
			ProductUnit:  nil,
			Sort:         int32(*dbCat.Sort),
			ProductCount: int32(*dbCat.ProductCount),
		}

		categoryMap[pbCat.ParentCid] = append(categoryMap[pbCat.ParentCid], pbCat)
	}

	rootCategories := s.buildCategoryTree(categoryMap, 0)

	return &pb.ListCategoryTreeResponse{
		Code: 200,
		Msg:  "success",
		Data: rootCategories,
	}, nil
}

func (s *CategoryService) UpdateCategorySort(ctx context.Context, req *pb.UpdateCategorySortRequest) (*pb.UpdateCategorySortResponse, error) {
	return &pb.UpdateCategorySortResponse{}, nil
}
